package com.sunday.aomicaichang.ui.my;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.event.EventBus;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.base.BaseApp;
import com.sunday.aomicaichang.http.ApiClient;
import com.sunday.member.entity.Member;
import com.sunday.member.utils.SignUtil;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by yun_sheng on 2017/6/6.
 */

public class UpdatePaySetting1Activity extends BaseActivity {
    @Bind(R.id.edt_phone)
    TextView edtPhone;
    @Bind(R.id.edt_code)
    EditText edtCode;
    @Bind(R.id.btn_code)
    TextView btnCode;
    @Bind(R.id.btn_ok)
    TextView btnOk;

    private static final int LOCK_SECS = 60;
    @Bind(R.id.title)
    TextView title;
    private StaticHandler mHander = null;
    private int lockCount = 0;
    private Timer mTimer = null;
    private TimerTask mTimeTask = null;
    private static final int UPDATE_COUNT_STATUS = 0;
    private String mobile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_pay1);
        ButterKnife.bind(this);
        mHander = new StaticHandler(this);
        mobile = BaseApp.getInstance().getMember().getMobile();
        if (mobile != null)
            edtPhone.setText(mobile);
        init();
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(edtCode.getText().toString())) {
                    ToastUtils.showToast(mContext, "请输入验证码");
                    return;
                }
                getData();
            }
        });
        title.setText("修改支付密码");
    }

    private void getData() {
        Call<ResultDO> call = ApiClient.getApiAdapter().check(mobile, 6,
                edtCode.getText().toString());
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                ResultDO<Member> resultDO = response.body();
                if (resultDO.getCode() == 0) {
                    Intent intent = new Intent(mContext, UpdatePaySetting2Activity.class);
                    intent.putExtra("code", edtCode.getText().toString());
                    startActivity(intent);
                    finish();
                } else {
                    ToastUtils.showToast(mContext, resultDO.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private void init() {
        btnCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCode();
            }
        });
    }

    private void sendCode() {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"mobile", "type", "nonce"};
        String[] str2 = new String[]{mobile, "6", nonce};
        showLoadingDialog(0);
        Call<ResultDO> call = ApiClient.getApiAdapter().send(mobile, 6,
                nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                ResultDO resultDO = response.body();
                if (resultDO.getCode() == 0) {
                    startCountdown(UPDATE_COUNT_STATUS);
                } else {
                    ToastUtils.showToast(mContext, resultDO.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private static class StaticHandler extends Handler {
        WeakReference<UpdatePaySetting1Activity> mActivity;

        StaticHandler(UpdatePaySetting1Activity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            UpdatePaySetting1Activity activity = mActivity.get();
            if (null == activity)
                return;

            if (msg.what == UPDATE_COUNT_STATUS) {
                activity.updateUICount();
                //
                if (activity.lockCount == LOCK_SECS) {
                    activity.stopCountdown(UPDATE_COUNT_STATUS);
                }
                activity.lockCount++;
            }
        }
    }

    private void startCountdown(final int id) {

        btnCode.setEnabled(false);
        if (mTimer == null)
            mTimer = new Timer();

        if (null != mTimeTask) {
            mTimeTask.cancel();
            mTimeTask = null;
        }

        if (mTimeTask == null) {
            mTimeTask = new TimerTask() {
                @Override
                public void run() {
                    sendUpdateUIMessage(id);
                }
            };
        }
        mTimer.schedule(mTimeTask, 0, 1000);

    }

    private void sendUpdateUIMessage(int id) {
        if (mHander != null) {
            Message message = Message.obtain(mHander, id);
            mHander.sendMessage(message);
        }
    }

    public void stopCountdown(int id) {
        if (null != mTimer) {
            mTimer.cancel();
            lockCount = 0;
            mTimer = null;
            mTimeTask = null;
        }
        btnCode.setEnabled(true);
        btnCode.setText("获取验证码");
    }

    private void updateUICount() {
        String str = "" + String.valueOf(LOCK_SECS - lockCount) + "";
        btnCode.setText(str + "s");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (null != mTimeTask) {
            mTimeTask.cancel();
            mTimeTask = null;
        }
        if (null != mTimer) {
            mTimer.cancel();
            mTimer = null;
        }
    }
}

